package huawei.window;

import java.util.HashMap;

/**
 * https://leetcode-cn.com/problems/fruit-into-baskets/
 */
public class J904 {
    public static void main(String[] args) {
        System.out.println(totalFruit(new int[]{3,3,3,1,2,1,1,2,3,3,4}));//5
        System.out.println(totalFruit(new int[]{1,2,3,2,2}));//4
        System.out.println(totalFruit(new int[]{0,1,2,2}));//3
        System.out.println(totalFruit(new int[]{1,2,1}));//3
    }
    public static int totalFruit(int[] fruits) {
        int left =0;
        int right = 0;
        int maxLen =0;
        HashMap<Integer,Integer> map=new HashMap<>();
        for (; right <fruits.length; right++) {
            map.put(fruits[right],map.getOrDefault(fruits[right],0)+1);
            while (map.size()>2){
                int c =map.get(fruits[left]);
                if(c>1){
                    map.put(fruits[left],c-1);
                }else {
                    map.remove(fruits[left]);
                }
                left++;
            }
            maxLen=Math.max(maxLen,right-left+1);
        }
        return maxLen;
    }
}
